#include <iostream>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
// #include "log.hpp"
#include <memory>

// std::string defaulthandler(const std::string &word, InetAddrModule::InetAddr &addr)
// {
//     // LOG(LogLevel::DEBUG) << "回调到了defaulthandler";
//     std::string s = "haha, ";
//     s += word;
//     return s;
// }

void Usage(std::string proc)
{
    std::cerr << "Usage :" << proc << "service_ip  service_port";
}

int main(int argc,char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }

    int port = std::stoi(argv[1]);
    // 申请文件描述符
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    if(sockfd < 0)
    {
        std::cerr << "socket fail" << std::endl;
        exit(1);
    }

    // 绑定
    //  int bind(int sockfd, const struct sockaddr *addr,
    //             socklen_t addrlen);
    struct sockaddr_in peer;
    // family（协议家族）
    peer.sin_family = AF_INET;
    // port
    peer.sin_port = htons(port);
    // ip
    peer.sin_addr.s_addr = INADDR_ANY;
    int n = bind(sockfd,(struct sockaddr*)&peer,sizeof(peer));
    if(n < 0)
    {
        std::cerr << "Bind Fail" << std::endl;
        exit(2);
    }

    // 将状态设为监听状态
    int m = listen(sockfd,5);
    if(m < 0)
    {
        std::cerr << "listen fail" << std::endl;
        exit(3);
    }

    struct sockaddr_in local;
    socklen_t len = sizeof(local);
    // 接受（其他主机的）链接。
    int fd = accept(sockfd,(struct sockaddr*)&local,&len);

    while(true)
    {
        // 先收再处理再发。
        char buffer[1024];
        int n = read(fd,buffer,sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << "收到了消息：" << buffer << std::endl;
        }

        std::string s = "Client Say#" + std::string(buffer);
        write(fd,s.c_str(),s.size());
    }
    return 0;
}